using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace BoxBinary.AspectCache.Core.Helpers
{
    /// <summary>
    /// A simple non-instanciable object with the only purpose to encrypt and
    /// decrypt strings
    /// </summary>
    internal sealed class Encryption64
    {
        private Encryption64()
        {
        }

        #region Methods

        /// <summary>
        /// Decrypts an encrypted string
        /// </summary>
        /// <param name="stringToDecrypt">String to decrypt</param>
        /// <param name="encryptionKey">Key used to encrypt the string</param>
        public static string Decrypt(string stringToDecrypt, string encryptionKey)
        {
            var key = new Byte[] {};
            Byte[] IV = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};

            var inputByteArray = new Byte[stringToDecrypt.Length];

            key = Encoding.UTF8.GetBytes(encryptionKey.Substring(0, 8));
            var des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(stringToDecrypt);
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            Encoding encoding = Encoding.UTF8;
            return encoding.GetString(ms.ToArray());
        }

        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="stringToEncrypt">String to encrypt</param>
        /// <param name="encryptionKey">Encryption key</param>
        public static string Encrypt(string stringToEncrypt, string encryptionKey)
        {
            var key = new Byte[] {};
            Byte[] IV = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};

            key = Encoding.UTF8.GetBytes(encryptionKey.Substring(0, 8));
            var des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }

        #endregion
    }
}